package com.wn.class30.adkTest;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;

@Controller
@RequestMapping("/sdkWechat")
@Slf4j
public class WechatController {
    @Resource
    private WxMpService wxMpService;

    @GetMapping("/authorize")//微信访问： http://yuhao.ngrok2.xiaomiqiu.cn/sdkWechat/authorize?returnUrl=https://www.baidu.com/
    public String authorize(String returnUrl){
        //配置
        //调用方法
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl("http://yuhao.ngrok2.xiaomiqiu.cn/sdkWechat/userInfo", WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        //【微信网页授权】，获取code，redirectUrl={}https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx010fdff474be73f4&redirect_uri=http%3A%2F%2Fyuhao.ngrok2.xiaomiqiu.cn%2FsdkWechat%2FuserInfo&
        // response_type=code&scope=snsapi_userinfo&state=https%3A%2F%2Fwww.baidu.com%2F#wechat_redirect
        log.info("【微信网页授权】，获取code，redirectUrl={}"+redirectUrl);
        return "redirect:"+redirectUrl;
    }
    @GetMapping("/userInfo")
    public String userInfo(String code,@RequestParam("state") String returnUrl){
        System.out.println("heheuserInfo");
        WxMpOAuth2AccessToken accessToken = null;
        try {
            accessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String openId = accessToken.getOpenId();
        System.out.println(accessToken);
        return "redirect:"+returnUrl+"?openid="+openId;//https://www.baidu.com/?openid=okbpCxGAKQFzIq2lDX0-_mo3EJG0
    }


}
